package com.lottery.im.util;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

/**
 * 小工具类
 *
 * @author ztz
 * 2017-10-24下午10:08:37
 */
public class MyUtils {

  /**
   * 比较版本号
   *
   * @return 0 1 不更新 -1 更新
   */
  public static int compareVersion(Context context, String version2) {
    String version1 = getVersionName(context);
    if (version1.equals(version2)) {
      return 0;
    }
    String[] version1Array = version1.split("\\.");
    String[] version2Array = version2.split("\\.");
    int index = 0;
    int minLen = Math.min(version1Array.length, version2Array.length);
    int diff = 0;
    while (index < minLen
        && (diff = Integer.parseInt(version1Array[index])
        - Integer.parseInt(version2Array[index])) == 0) {
      index++;
    }
    if (diff == 0) {
      for (int i = index; i < version1Array.length; i++) {
        if (Integer.parseInt(version1Array[i]) > 0) {
          return 1;
        }
      }
      for (int i = index; i < version2Array.length; i++) {
        if (Integer.parseInt(version2Array[i]) > 0) {
          return -1;
        }
      }
      return 0;
    } else {
      return diff > 0 ? 1 : -1;
    }
  }

  /**
   * 获取版本号
   */
  public static String getVersionName(Context context) {
    try {
      PackageManager packageManager = context.getPackageManager();
      PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
      return packInfo.versionName;
    } catch (PackageManager.NameNotFoundException e) {
      e.printStackTrace();
    }
    return "";
  }
}
